import { hostUrl, USER_ACCESS_TOKEN } from '@/libs/config.js';
import { showToast } from '@/utils/utils.js';

let miniProgram = {};
if (uni.getAccountInfoSync) {
  miniProgram = uni.getAccountInfoSync();
}
let requestCount = 0;
let showLoadingTimer = null;
let showFailTimer = null;
let isLoading = false;
const httpRequest = options => {
  const { url, method = 'GET', data = {} } = options;
  requestCount++;
  for (const key in data) {
    if (data[key] === undefined || data[key] === null || data[key] === '' || ['isLoadAll'].includes(key)) {
      delete data[key];
    }
  }
  const header = options.header || {};
  const token = uni.getStorageSync(USER_ACCESS_TOKEN);
  if (token) {
    header.Authorization = `Bearer ${token}`;
  }
  // 关联客户
  const userInfo = uni.getStorageSync('userInfo');
  if (userInfo?.customer_id) {
    data.customer_id = userInfo.customer_id;
  }
  clearTimeout(showLoadingTimer);
  showLoadingTimer = setTimeout(() => {
    if (requestCount > 0) {
      isLoading = true;
      uni.showLoading({
        title: '加载中…',
        mask: true,
      });
    }
  }, 3000);
  return new Promise((resolve, reject) => {
    uni.request({
      url: hostUrl + url,
      data,
      method,
      header,
      timeout: 5000,
      success(res) {
        const { statusCode, header = {}, data = {} } = res;
        if (header.authorization) {
          uni.setStorageSync(USER_ACCESS_TOKEN, header.authorization);
        }
        const { code, message } = data;
        if (statusCode >= 500) {
          if (miniProgram.envVersion === 'release') {
            showToast('网络错误，请重试！');
            resolve(data);
          } else {
            showToast(message);
            resolve(data);
          }
          return;
        }
        // token失效
        if (code === 10401) {
          showToast('登录已过期，请重新登录');
          uni.clearStorageSync();
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/index',
            });
          }, 1000);
          return;
        } else if (code && code !== 200) {
          showToast(message);
        } else if (!code) {
          showToast('网络错误，请重试！');
        }
        resolve(data);
      },
      fail(error) {
        showToast('网络错误，请重试！');
        reject(error);
      },
      complete() {
        checkLoading();
      },
    });
  });
};

// 关闭loading
function checkLoading() {
  requestCount--;
  clearTimeout(showFailTimer);
  if (requestCount <= 0) {
    requestCount = 0;
    isLoading && uni.hideLoading();
    isLoading = false;
  }
  showFailTimer = setTimeout(() => {
    if (requestCount > 0) {
      requestCount = 0;
      isLoading && uni.hideLoading();
      isLoading = false;
      // showToast('网络超时');
    }
  }, 10 * 1000);
}

export default httpRequest;
